import request from '@/utils/request'

/**
 * 单图片上传
 * @param {File} file 图片文件
 * @returns {Promise} 返回上传结果
 */
export function uploadImage(file) {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/v6/upload/image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 批量图片上传
 * @param {FileList} files 图片文件列表
 * @returns {Promise} 返回上传结果
 */
export function uploadImages(files) {
  const formData = new FormData()
  
  // 添加多个文件
  Array.from(files).forEach(file => {
    formData.append('files[]', file)
  })
  
  return request({
    url: '/v6/upload/images',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除图片
 * @param {string} url 图片URL
 * @returns {Promise} 返回删除结果
 */
export function deleteImage(url) {
  return request({
    url: '/v6/upload/deleteImage',
    method: 'post',
    data: { url }
  })
}

/**
 * 获取图片信息
 * @param {string} url 图片URL
 * @returns {Promise} 返回图片信息
 */
export function getImageInfo(url) {
  return request({
    url: '/v6/upload/getImageInfo',
    method: 'get',
    params: { url }
  })
}

/**
 * Base64图片上传
 * @param {string} base64Data Base64图片数据
 * @param {string} filename 文件名
 * @returns {Promise} 返回上传结果
 */
export function uploadBase64Image(base64Data, filename = 'image.png') {
  // 将base64转换为Blob
  const byteCharacters = atob(base64Data.split(',')[1])
  const byteNumbers = new Array(byteCharacters.length)
  
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  
  const byteArray = new Uint8Array(byteNumbers)
  const blob = new Blob([byteArray], { type: 'image/png' })
  
  const formData = new FormData()
  formData.append('file', blob, filename)
  
  return request({
    url: '/v6/upload/image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
